package com.browser.bookmark.auth;

import com.browser.bookmark.entity.User;
import com.browser.bookmark.service.IUserService;
import com.browser.bookmark.utils.JWTUtil;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;

import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;
import java.util.UUID;


/**
 * @Auther: Wang
 * @Date: 2020/02/06 19:09
 * 功能描述:
 */


public class ShiroRealm extends AuthorizingRealm {
    private static final Logger logger = LoggerFactory.getLogger(ShiroRealm.class);

    @Autowired
    private IUserService userService;


    /**
     * 使用JWT替代原生Token
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }




    // 用户赋于相关权限
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        logger.info("======================= 开始角色授权 ======================");
        //1. 从 PrincipalCollection 中来获取登录用户的信息
        String username = JWTUtil.getUsername((String) SecurityUtils.getSubject().getPrincipal());

        //2.添加角色和权限
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        Set<String> stringSet = new HashSet<>();
        if(username.equals("admin")){
            stringSet.add("user:admin");
            stringSet.add("user:show");
        }else {
            stringSet.add("user:show");
        }
        logger.info("======================= 读取{"+username+"}该角色的权限 ======================");
        for (String str : stringSet) {
            System.out.println(str);
        }

        simpleAuthorizationInfo.setStringPermissions(stringSet);
        return simpleAuthorizationInfo;

    }



    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth)
            throws AuthenticationException {
        logger.info("======================= 认证登陆 ======================");
        String token = (String) auth.getCredentials();
        // 解密获得username，用于和数据库进行对比
        String username = JWTUtil.getUsername(token);
        if (username == null) {
            throw new AuthenticationException("token无效");
        }
        User user= userService.selectUser(username);
        if (user.getUserId() == null) {
            System.out.println("用户不存在");
            throw new AuthenticationException("用户不存在!");
        }
        if (! JWTUtil.verify(token, username, user.getPassword())) {
            System.out.println("用户名或密码错误");
            throw new AuthenticationException("用户名或密码错误");
        }
        //当前realm对象的name
        String realmName = getName();

        return new SimpleAuthenticationInfo(token, token, realmName);
    }


//    public static void main(String[] args) {
//        String hashAlgorithName = "MD5";
//        String password = "666666";
//        int hashIterations = 1024;//加密次数
//        String str= RandomStringUtils.randomAlphanumeric(5);
//        System.out.println(str);
//        ByteSource credentialsSalt = ByteSource.Util.bytes("admin123"+str);
//        Object obj = new SimpleHash(hashAlgorithName, password, credentialsSalt, hashIterations).toHex();
//        System.out.println(obj);
//    }

}
